package com.lamatek.tags.google.beans;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;

/**
 * Ip2GeoCoder 
 * @author Tom Cole
 * @version 0.40
 * 
 * This implementation of IPCoder attempts to geocode an IP address using
 * the Ip2Geo web service.
 * 
 * Developers should not override this method, but should rather create their
 * own classes that implement IPCoder.
 */
public class Ip2GeoCoder implements IPCoder, Serializable { 
    
    String ip = null;
    double longitude = 0.00d;
    double latitude = 0.00d;
    
    public void setIp(String ip) {
        this.ip = ip;
    }
    public boolean geocode() {
        if (ip == null) {
            return false;
        }
        else {
            try {
                String path = "http://ws.cdyne.com/ip2geo/ip2geo.asmx/ResolveIP?IPAddress=" + ip + "&LicenseKey=0";
	            URL url = new URL(path);
	            URLConnection con = url.openConnection();
	            BufferedReader input = new BufferedReader(new InputStreamReader(con.getInputStream()));
	            String line = "";
	            while ((line = input.readLine()) != null) {
	                if (line.indexOf("<Latitude>") >= 0) {
	                    int start = line.indexOf(">") + 1;
	                    int stop = line.indexOf("<", start);
	                    latitude = Double.parseDouble(line.substring(start, stop).trim());
	                }
	                else if (line.indexOf("<Longitude>") >= 0) {
	                    int start = line.indexOf(">") + 1;
	                    int stop = line.indexOf("<", start);
	                    longitude = Double.parseDouble(line.substring(start, stop).trim());
	                }
	            }
	            input.close();
	            return true;
            }
            catch(Exception ex) {
                ex.printStackTrace(System.err);
                return false;
            } 
        }
    }
    public double getLongitude() {
        return longitude;
    }
    public double getLatitude() {
        return latitude;
    }
}
